package com.sbwebsocket.core.ws;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbwebsocket.core.model.bo.NormalMessageBody;
import com.sbwebsocket.core.model.bo.WsMessage;
import com.sbwebsocket.core.service.ClientManager;
import com.sbwebsocket.core.service.MessageQueueAdapter;
import com.sbwebsocket.core.service.OfflineMessageManager;
import com.sbwebsocket.core.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: GSJ
 * @Date: 2022/2/10
 * @Description:
 * @version: 1.0
 */
@Slf4j
@ServerEndpoint("/socket/{clientKey}")
public class WebSocketServer {
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<String, WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private ObjectMapper objectMapper;

    private ClientManager clientManager;

    private MessageQueueAdapter messageQueueAdapter;

    private OfflineMessageManager offlineMessageManager;

    public String getClientKey() {
        return clientKey;
    }

    //用户身份标志key
    private String clientKey;

    @Autowired
    public WebSocketServer(ObjectMapper objectMapper, ClientManager clientManager, MessageQueueAdapter messageQueueAdapter, OfflineMessageManager offlineMessageManager) {
        this.objectMapper = objectMapper;
        this.clientManager = clientManager;
        this.messageQueueAdapter = messageQueueAdapter;
        this.offlineMessageManager = offlineMessageManager;
    }

    public WebSocketServer() {
        //订阅自身主题
        this.objectMapper = SpringUtil.getBean(ObjectMapper.class);
        this.clientManager = SpringUtil.getBean(ClientManager.class);
        this.messageQueueAdapter = SpringUtil.getBean(MessageQueueAdapter.class);
        this.offlineMessageManager = SpringUtil.getBean(OfflineMessageManager.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clientKey") String clientKey) {
        this.session = session;
        this.clientKey = clientKey;
        webSocketMap.put(clientKey, this);     //加入set中
        clientManager.registerUserConnection(clientKey);
        try {
            sendMessage(offlineMessageManager.find(clientKey));
        } catch (Exception e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        try {
            log.debug("客户端:{}下线!", this.clientKey);
            clientManager.cleanUserConnection(this.clientKey);
            webSocketMap.remove(this);  //从set中删除
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息,必须为：WsMessage类型
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            WsMessage wsMessage = objectMapper.readValue(message, WsMessage.class);
            log.info("收到的信息:" + message);
            NormalMessageBody messageBody = (NormalMessageBody) objectMapper.readValue(wsMessage.getMsg(), wsMessage.getType().getMessageBodyClz());
            messageQueueAdapter.get(messageBody).delivery(messageBody);
        } catch (JsonProcessingException e) {
            log.error("发送消息失败：", e);
//            e.printStackTrace();
        }
    }

//    @OnMessage
//    public void onMessage(String message, Session session) {
//        log.info("收到的信息:"+message);
//        Map<String, Object> maps = new HashMap<>();
//        maps.put("type", message);
//        sendInfo(maps);
//    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object obj) throws Exception {
//        try {
//            synchronized (this.session) {
        this.session.getBasicRemote().sendText(objectMapper.writeValueAsString(obj));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(Object obj) {
        for (WebSocketServer item : webSocketMap.values()) {
            try {
                item.sendMessage(obj);
            } catch (Exception e) {
                continue;
            }
        }
    }

}
